﻿using System;
using System.Xml;
namespace Utility
{
    public class Config
    {
        string ConfigFile { get; set; }
        XmlDocument Doc=new XmlDocument();
        public Config(string _ConfigFile)
        {
            Doc.Load(_ConfigFile);
            ConfigFile = _ConfigFile;
        }

        #region 读取配置文件的所有设置节点
        /// <summary>
        /// 读取配置文件的所有设置节点
        /// </summary>
        /// <param name="_NodeStr"></param>
        /// <returns></returns>
        public XmlNodeList ConfigGetXmlNodeList(string _NodeStr)
        {
            try
            {
                return this.Doc.SelectNodes(_NodeStr);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }
        #endregion

        #region 读取配置文件的参数
        /// <summary>
        /// 读取配置文件的参数
        /// </summary>
        /// <param name="_ConfigFile"></param>
        /// <param name="_Key"></param>
        /// <returns></returns>
        public string ConfigGetValue(string _Key)
        {
            try
            {
                XmlNode XNode;
                XmlElement XElem;
                XNode = Doc.SelectSingleNode("//appSettings");
                XElem = (XmlElement)XNode.SelectSingleNode("//add[@key='" + _Key + "']");
                if (XElem != null)
                {
                    return XElem.GetAttribute("value");
                }
                else
                {
                    return "";
                }
            }
            catch(Exception)
            {
                return "";
            }
        }
        #endregion

        #region 设置配置文件的参数
        public void ConfigSetValue(string _Key, string _Val)
        {
            XmlNode XNode;
            XmlElement XElem;
            XNode = Doc.SelectSingleNode("//appSettings");
            XElem = (XmlElement)XNode.SelectSingleNode("//add[@key='" + _Key + "']");
            if (XElem != null)
            {
                XElem.SetAttribute("value", _Val);
            }
            else
            {
                XmlElement Xm = Doc.CreateElement("add");
                Xm.SetAttribute("key" , _Key);
                Xm.SetAttribute("value" , _Val);
                XNode.AppendChild(Xm);
            }
            Doc.Save(ConfigFile);
        }
        #endregion
    }

}
